package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.zzyl.constant.CacheConstant;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.ResourceVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 权限表服务实现类
 */
@Service
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    /**
     * 资源树形
     *
     * @param resourceDto 查询条件
     * @return: TreeVo
     */
    @Cacheable(value = CacheConstant.RESOURCE_TREE)
    @Override
    public TreeVo resourceTreeVo(ResourceDto resourceDto) {

        //1.构建查询条件
        ResourceDto dto = ResourceDto.builder().dataState(SuperConstant.DATA_STATE_0)
                .parentResourceNo(NoProcessing.processString(SuperConstant.ROOT_PARENT_ID))
                .resourceType(SuperConstant.MENU)
                .build();

        //2.查询所有资源数据
        List<Resource> resourceList = resourceMapper.selectList(dto);
        if (EmptyUtil.isNullOrEmpty(resourceList)) {
            throw new RuntimeException("资源信息未定义");
        }

        //3.定义返回的树形集合
        List<TreeItemVo> itemVos = new ArrayList<>();

        //4.使用hutool工具获取树形结构
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        //自定义名称由原有的name改成label
        treeNodeConfig.setNameKey("label");
        //利用hutool中的树形菜单功能实现
        List<Tree<String>> treeList = TreeUtil.build(resourceList, SuperConstant.ROOT_PARENT_ID, treeNodeConfig, (resource, treeNode) -> {
            treeNode.setName(resource.getResourceName());
            treeNode.setId(resource.getResourceNo());
            treeNode.setParentId(resource.getParentResourceNo());
        });
        //5.集合泛型转换
        List<TreeItemVo> children = BeanUtil.copyToList(treeList, TreeItemVo.class);
        //6.由于没有根节点，构建跟节点信息
        TreeItemVo itemVo = TreeItemVo.builder().id(SuperConstant.ROOT_PARENT_ID).label("智慧养老院").children(children).build();
        //7.封装到树形集合中
        itemVos.add(itemVo);
        //数据返回
        return TreeVo.builder().items(itemVos).build();
    }

    /**
     * 多条件查询资源列表
     *
     * @param resourceDto
     * @return
     */
    @Cacheable(value = CacheConstant.RESOURCE_LIST, key = "#resourceDto.hashCode()")
    @Override
    public List<ResourceVo> findResourceList(ResourceDto resourceDto) {
        List<Resource> resourceList = resourceMapper.selectList(resourceDto);
        return BeanUtil.copyToList(resourceList, ResourceVo.class);
    }

    /**
     * 添加资源菜单
     *
     * @param resourceDto
     * @return
     */
    @Caching(evict = {@CacheEvict(value = CacheConstant.RESOURCE_LIST, allEntries = true),
            @CacheEvict(value = CacheConstant.RESOURCE_TREE, allEntries = true)})
    @Override
//    @Caching(evict = {
//            @CacheEvict(value = CacheConstant.RESOURCE_LIST,allEntries = true),
//            @CacheEvict(value = CacheConstant.RESOURCE_LIST,allEntries = true)
//    })
    public void createResource(ResourceDto resourceDto) {
        //2.类型转换拷贝
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        //3.同步父资源状态和子资源状态一致
        Resource parentResourceNo = resourceMapper.selectByResourceNo(resource.getParentResourceNo());
        resource.setDataState(parentResourceNo.getDataState());

        //4.添加子资源编号
        String resourceNo = createResourceNo(resource);
        resource.setResourceNo(resourceNo);

        //1.调用新增mapper接口
        resourceMapper.insert(resource);
    }

    /**
     * 资源修改
     *
     * @param resourceDto
     */
    @Override
    @Caching(evict = {@CacheEvict(value = CacheConstant.RESOURCE_LIST, allEntries = true),
            @CacheEvict(value = CacheConstant.RESOURCE_TREE, allEntries = true)})
    public boolean updateResource(ResourceDto resourceDto) {
        //类型转换
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        //更新资源

        resourceMapper.updateResource(resource);

        return true;
    }

    /**
     * 修改状态
     *
     * @param resourceDto
     * @return boolean
     */
    @Override
    @Caching(evict = {@CacheEvict(value = CacheConstant.RESOURCE_LIST, allEntries = true),
            @CacheEvict(value = CacheConstant.RESOURCE_TREE, allEntries = true)})
    public boolean isEnable(ResourceDto resourceDto) {
        //启用菜单
        if (resourceDto.getDataState().equals("0")) {
            //判断父级菜单是否是禁用，如果是禁用，不允许启用
            String parentResourceNo = resourceDto.getParentResourceNo();
            Resource parentResource = resourceMapper.selectByResourceNo(parentResourceNo);
            if (parentResource != null && parentResource.getDataState().equals("1")) {
                throw new BaseException(BasicEnum.PARENT_MENU_DISABLE);
            }
        }

        //判断是否有子菜单，如果有子菜单，则一起启用或禁用
        String resourceNo = resourceDto.getResourceNo();
        resourceMapper.updateByResourceNo(resourceNo, resourceDto.getDataState());
        resourceMapper.updateByParentResourceNo(NoProcessing.processString(resourceNo), resourceDto.getDataState());
        return true;
    }

    /**
     * 删除资源
     *
     * @param menuId
     */
    @Caching(evict = {@CacheEvict(value = CacheConstant.RESOURCE_LIST, allEntries = true),
            @CacheEvict(value = CacheConstant.RESOURCE_TREE, allEntries = true)})
    @Override
    public void deleteResource(String menuId) {
        //根据传来的编号查询资源
        Resource resource = resourceMapper.selectByResourceNo(menuId);
        System.out.println("=============================================");
        System.out.println(resource);
        System.out.println("=============================================");
        //查询是否有子资源
        ResourceDto dto = ResourceDto
                .builder()
                .parentResourceNo(NoProcessing.processString(resource.getResourceNo()))
                .build();
        List<Resource> resourceList = resourceMapper.selectList(dto);
        System.out.println("=============================================");
        System.out.println(resourceList);
        System.out.println("=============================================");
        //判断是否有子资源如果有则抛出异常
        if (resourceList.size() > 0) {
            throw new RuntimeException("有子菜单，不能删除此菜单");
        }
        //删除资源
        resourceMapper.deleteByNo(resource.getResourceNo());


    }


    /**
     * 添加子资源编号方法
     *
     * @param resource
     * @return
     */
    private String createResourceNo(Resource resource) {
        /**
         * 1、如果是菜单，以及父资源编号是否大于三级
         */
        if (resource.getResourceType().equals("m") &&
                NoProcessing.processString(resource.getParentResourceNo()).length() / 3 >= 5) {
            throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
        }
        //2.不大于三级，查询父资源编号下是否包含子资源
        ResourceDto dto = ResourceDto.builder().parentResourceNo(resource.getParentResourceNo()).build();
        List<Resource> resourceList = resourceMapper.selectList(dto);

        if (EmptyUtil.isNullOrEmpty(resourceList)) {
            //3.父资源编号下没有下属节点，则新增  100 001 001 001 000--->新增下属节点100 001 001 001 001
            return NoProcessing.createNo(resource.getParentResourceNo(), false);
        } else {
            //4.有下属节点，则在原有基础上追加 100 001 001 001 001--->追加之后，100 001 001 001 002
            //要先获取下属节点中的最大值
            Long maxNo = resourceList.stream().map(resource1 -> {
                return Long.valueOf(resource1.getResourceNo());
            }).max(Comparator.comparing(Long::intValue)).get();
            return NoProcessing.createNo(String.valueOf(maxNo), true);
        }
    }


}